/**
 * AI 助手 Hook
 */

import { useCallback, useState } from 'react';
import { useProofMapper } from '@/contexts/ProofMapper';
import { showMessage } from '@/components/common/MessageTip';
// import { proofMapperAPI } from '@/api/proofMapper';
import type { AIAdjustmentCommand } from '@/types/ProofMapper';

export const useAIAssistant = () => {
  const {
    evaluationItems,
    aiInputValue,
    adjustmentCommands,
    addAdjustmentCommand,
    setEvaluationItems,
    setAiInput,
    setLoading
  } = useProofMapper();

  const [processing, setProcessing] = useState(false);

  const executeCommand = useCallback(async (command: string) => {
    if (!command.trim()) {
      showMessage('warning', '请输入调整指令');
      return;
    }

    setProcessing(true);
    setLoading(true);

    try {
      // 创建调整指令记录
      const adjustmentCommand: AIAdjustmentCommand = {
        id: `cmd-${Date.now()}`,
        command: command.trim(),
        type: 'modify',
        executed: false,
        created_at: new Date().toISOString()
      };

      addAdjustmentCommand(adjustmentCommand);

      // 调用真实的AI调整API（目前使用模拟逻辑）
      // const response = await proofMapperAPI.executeAdjustment(command);
      
      // 模拟AI处理过程
      await new Promise(resolve => setTimeout(resolve, 2000));

      // 模拟不同类型的调整结果
      let result = '';
      let updatedItems = [...evaluationItems];

      if (command.includes('合并') && command.includes('日志')) {
        result = '已将系统日志、访问日志和安全日志合并为统一的日志审计要求';
        updatedItems = updatedItems.map(item => {
          if (item.module === '日志审计') {
            return {
              ...item,
              materials: ['系统操作日志', '访问控制日志', '安全事件日志', '日志存储配置', '日志完整性验证'],
              notes: '统一的日志审计要求，包含所有系统日志类型',
              updated_at: new Date().toISOString()
            };
          }
          return item;
        });
      } else if (command.includes('增加') && command.includes('加密')) {
        result = '已添加传输层加密和端到端加密的具体要求';
        updatedItems = updatedItems.map(item => {
          if (item.module === '数据加密') {
            return {
              ...item,
              materials: [...item.materials, '端到端加密配置', '传输层安全协议文档'],
              notes: '确保使用TLS 1.3及以上版本，支持端到端加密',
              updated_at: new Date().toISOString()
            };
          }
          return item;
        });
      } else if (command.includes('删除') && command.includes('重复')) {
        result = '已检查并删除重复的评估项目';
        // 实现去重逻辑
        const seen = new Set<string>();
        updatedItems = updatedItems.filter(item => {
          const key = `${item.module}-${item.checkpoint}`;
          if (seen.has(key)) {
            return false;
          }
          seen.add(key);
          return true;
        });
      } else if (command.includes('重要性') || command.includes('优先级')) {
        result = '已按照安全重要性对评估项进行重新排序';
        const priorityMap: Record<string, number> = {
          '身份认证': 1,
          '数据加密': 2,
          '访问控制': 3,
          '漏洞管理': 4,
          '日志审计': 5,
          '数据备份': 6
        };
        updatedItems = [...updatedItems].sort((a, b) => {
          return (priorityMap[a.module] || 99) - (priorityMap[b.module] || 99);
        });
      } else {
        result = `已根据指令"${command}"对评估清单进行相应调整`;
      }

      // 更新调整指令状态
      const updatedCommand: AIAdjustmentCommand = {
        ...adjustmentCommand,
        executed: true,
        result
      };

      addAdjustmentCommand(updatedCommand);
      setEvaluationItems(updatedItems);
      setAiInput('');
      
      showMessage('success', 'AI调整完成');

    } catch (error) {
      showMessage('error', 'AI调整失败，请重试');
      console.error('AI adjustment error:', error);
    } finally {
      setProcessing(false);
      setLoading(false);
    }
  }, [evaluationItems, addAdjustmentCommand, setEvaluationItems, setAiInput, setLoading]);

  const getQuickSuggestions = useCallback(() => {
    return [
      '合并所有日志类材料',
      '增加数据传输环节的加密要求',
      '按重要性排序',
      '删除重复项',
      '添加高风险项目',
      '更新备注信息格式'
    ];
  }, []);

  return {
    executeCommand,
    processing,
    quickSuggestions: getQuickSuggestions(),
    inputValue: aiInputValue,
    setInputValue: setAiInput,
    adjustmentHistory: adjustmentCommands
  };
};
